﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Domain.CommonModel.TreeLike;

namespace Happy.Dto.CommonModel.TreeLike
{
    /// <summary>
    /// 扩展类型。
    /// </summary>
    public static class ITreeNodeViewExtentions
    {
        /// <summary>
        /// 返回节点所在的层级。
        /// </summary>
        public static int GetNodeLevel<T, TId>(this T that)
            where T : ITreeNodeView<TId>
            where TId : struct
        {
            return that.NodePath.Count(x => x.ToString() == TreeNodeConstant.NodePathSeparator);
        }

        /// <summary>
        /// 将节点按照前序遍历的顺序进行排序，用来显示在下拉框中。
        /// </summary>
        public static IEnumerable<T> PreOrderSort<T, TId>(this IEnumerable<T> that)
            where T : ITreeNodeView<TId>
            where TId : struct
        {
            var rawList = that.ToList();
            var resultList = new List<T>();

            PreOrderSort<T, TId>(rawList, resultList, null);

            return resultList;
        }

        private static void PreOrderSort<T, TId>(List<T> rawList, List<T> resultList, TId? parentId)
            where T : ITreeNodeView<TId>
            where TId : struct
        {
            var children = rawList.Where(x => x.ParentId.Equals(parentId)).ToList();


            foreach (var item in children)
            {
                rawList.Remove(item);
                resultList.Add(item);
                PreOrderSort<T, TId>(rawList, resultList, item.Id);
            }
        }
    }
}
